<?php
/**
 * tpshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 * ============================================================================
 * $Author: 当燃 2016-01-09
 */
namespace Mobile\Controller;
class IndexController extends MobileBaseController {

    public function index(){


        //获取微信配置
        $wechat_list = M('wx_user')->select();
        $wechat_config = $wechat_list[0];
        $this->weixin_config = $wechat_config;
        // 微信Jssdk 操作类 用分享朋友圈 JS
        $jssdk = new \Mobile\Logic\Jssdk($this->weixin_config['appid'], $this->weixin_config['appsecret']);
        $signPackage = $jssdk->GetSignPackage();
        $user=$_SESSION['user'];
        $this->assign('user',$user);
        $hot_goods = M('goods')->where("is_hot=1 and is_on_sale=1")->order('goods_id DESC')->limit(20)->cache(true,TPSHOP_CACHE_TIME)->select();//首页热卖商品
        $thems = M('goods_category')->where('level=1')->order('sort_order')->limit(9)->cache(true,TPSHOP_CACHE_TIME)->select();
        $this->assign('thems',$thems);
        $this->assign('hot_goods',$hot_goods);
        $favourite_goods = M('goods')->where("is_recommend=1 and is_on_sale=1")->order('goods_id DESC')->limit(20)->cache(true,TPSHOP_CACHE_TIME)->select();//首页推荐商品
        $this->assign('favourite_goods',$favourite_goods);
        $this->assign('signPackage',$signPackage);
        $this->assign('navid',"home"); //存储用户信息

        //在线人数统计
        $a_time = strtotime(date('Y-m-d', time()));
        $e_time = 60*60*24+$a_time;
        //当天进入开门的所有数量
        $j_where['cate_id']=1;
        $j_where['add_time']=array(array('lt',$e_time),array('gt',$a_time),'and');
        $j_num =M('open_door_log')->where($j_where)->count();
        //  当天出去开门的所有数量
        $j_where['cate_id']=2;
        $c_num =M('open_door_log')->where($j_where)->count();
        $on_live_num=$j_num-$c_num;
        //当在线人数小于16的时候  取16-20的随机数作为在线人数
        if($on_live_num<16)
            $on_live_num=rand(16,20);
        $this->assign('on_live_num',$on_live_num);
        $this->display();
    }




    /**
     * 进入开门
     */
    public function begin_open(){

        $user_id=$_SESSION['user']['user_id'];
        if(!$user_id){
            $this->error('用户不存在！');
        }

        $user=M('users')->where("user_id=$user_id")->find();
        $coach=M('coach')->where("user_id=$user_id")->find();
        if($coach){
            //教练(管理员)直接执行开门
            $res =  open_door($user_id,1,4);
        }else { //普通用户   echo 1111;exit;

            $today = date('Ymd');
            if ($user['is_member'] && $today < $user['member_endtime']) {//vip会员(并在有效期内)执行开门
                $res = open_door($user_id, 1, 1);

            } elseif ($user['once_num'] > 0) {//次卡用户（并且次数大于0）执行开门
                $res = open_door($user_id, 1, 2);

            } elseif ($user['old_member_endtime'] > $today) {//旧用户免费期内开门执行开门
                $res = open_door($user_id, 1, 6);

            } else {//普通用户
                $open_status=select_order_status($user_id);//查询是否有未支付的订单
                if($open_status){
                    $data['user_id'] = $user_id;
                    $data['date'] = date("Ymd");
                    $data['start_time'] = time();
                    $data['add_time'] = time();
                    $data['mobile'] = $user['mobile'];
                    $data['order_sn'] = getrand_num();
                    $data['type_id'] = 2;
                    $data['end_time'] = 0;

                    $order_id = M('order')->add($data);
                    if ($order_id) {
                        //订单生成成功后执行开门
                        $res = open_door($user_id, 1, 3);//普通时常订单用户开门

                        if ($res->code == '0') {
                            $arr['status']=1;
                            $arr['msg']='欢迎光临';
                            exit(json_encode($arr));
//                                $this->success('欢迎光临',U('Mobile/Index/index'));
                        } else {
                            $arr['status']=1;
                            $arr['msg']='-1002 网络故障，请联系管理员，切勿重复扫码！';
                            exit(json_encode($arr));
//                                $this->error('-1002 网络故障，请联系管理员，切勿重复扫码！',U('Mobile/Index/index'));
                        }
                    } else {
                        $arr['status']=1;
                        $arr['msg']='-1001 开门失败，请联系管理员！';
                        exit(json_encode($arr));
//                            $this->error('-1001 开门失败，请联系管理员！',U('Mobile/Index/index'));
                    }
                }else{

                    $arr['status']=-2;
                    $arr['msg']='您有未支付订单，支付后方可进入！';
                    exit(json_encode($arr));

//                        $this->error('您有未支付订单，支付后方可进入！',U('/Mobile/User/order_list',array('type'=>'WAITPAY')));
                }


            }

            //特殊会员不生成时长订单的开门状态返回码
            if(is_object($res)){
                if ($res->code == '0') {
                    $arr['status']=1;
                    $arr['msg']='欢迎光临！';
                    exit(json_encode($arr));
//                    $this->success('欢迎光临',U('Mobile/Index/index'));
                } else {
                    $arr['status']=1;
                    $arr['msg']='-1001 开门失败，请联系管理员！';
                    exit(json_encode($arr));
//                    $this->error('-1002 网络故障开门失败，请重试！',U('Mobile/Index/index'));
                }
            }elseif($res['status']=='-101'){
                $arr['status']=1;
                $arr['msg']='-1003 '.$res['msg'];
                exit(json_encode($arr));
//                $this->error('-1003 '.$res['msg'],U('Mobile/Index/index'));
            }
        }
        //教练开门状态返回码
        if ($res->code == '0') {
            $arr['status']=1;
            $arr['msg']='欢迎光临';
            exit(json_encode($arr));
//            $this->error('-1002 网络故障开门失败，请重试！',U('Mobile/Index/index'));exit;
        } else {
            $arr['status']=1;
            $arr['msg']='-1002 网络故障开门失败，请重试！';
            exit(json_encode($arr));
//            $this->success('欢迎光临',U('Mobile/Index/index'));
        }
    }

    /**
     * 结束开门
     */

    public function end_open(){
        $user_id=$_SESSION['user']['user_id'];
        $user=M('users')->where("user_id=$user_id")->find();
        if(!$user){
            $this->error('用户不存在！');
        }
        $coach=M('coach')->where("user_id=$user_id")->find();
        if($coach){
            //教练 直接执行开门
            $res =  open_door($user_id,2,4);
        }else {   //普通用户
            $today = date('Ymd');
            if ($user['is_member'] && $today < $user['member_endtime']) {//特殊会员(并在有效期内) 执行开门
                $res = open_door($user_id, 2, 1);
            } elseif ($user['once_num'] > 0) {//次卡用户（并且次数大于0）执行开门
                $res = open_door($user_id, 2, 2);
            } elseif ($user['old_member_endtime'] > $today) {//旧用户免费期内开门执行开门
                $res = open_door($user_id, 2, 6);
            } else {

                //订单支付
                $where['user_id']=$user_id;
                $where['pay_status']=0;
                $where['order_status']=0;
                $where['type_id']=2;
                $where['date']=date("Ymd");
                $order=M('order')->order('order_id DESC')->where($where)->find();
                //计算订单价格
                if($order){
                    $config = tpCache('charge_info');
                    $minute_charge=$config['minute_charge'];//配置的每分钟收费单价
                    $upper_charge=$config['upper_charge'];//单日封顶价
                    if($order['order_amount']==$upper_charge){//订单价格是20元的

                        $arr['status']=2;
                        $arr['order_id']=$order['order_id'];
                        $arr['msg']='已生成订单';
                        exit(json_encode($arr));

//                        $this->success('已生成订单',U('Mobile/Cart/cart4',array('order_id'=>$order['order_id'])));
                    }else{//订单价格不是20元的，重新计算价格
                        $min_num =ceil((time()-$order['start_time'])/60);//进入的分钟数(进一法取整)
                        $order_money=$min_num*$minute_charge;//生成订单的总价
                        $order_money>$upper_charge?$order_amount=$upper_charge:$order_amount=$order_money;
                        if( $order_amount<0.01)
                            $order_amount=0.01;
                        $order_id=$order['order_id'];
                        $up_data['order_id']=$order['order_id'];
                        $up_data['order_amount']=$order_amount;
                        $up_data['end_time']=time();
                        $res=M('order')->save($up_data);


                        $arr['status']=2;
                        $arr['order_id']=$order_id;
                        $arr['msg']='已生成订单';
                        exit(json_encode($arr));

//                        $this->success('已生成订单',U('Mobile/Cart/cart4',array('order_id'=>$order_id)));
                    }
                }else{
                    //扫出去的码的时候。没有查询到有进来的记录的属于非法操作，需要支付单日上限的罚金
                    $config = tpCache('charge_info');
                    $upper_charge=$config['upper_charge'];//单日封顶价
                    $add_data['user_id']=$_SESSION['user']['user_id'];
                    $add_data['order_amount']=$upper_charge;//单日上限金额
                    $add_data['date'] = date("Ymd");
                    $add_data['add_time'] = time();
                    $add_data['mobile'] = $user['mobile'];
                    $add_data['order_sn'] = getrand_num();
                    $add_data['type_id'] = 2;
                    $add_data['type_2_id'] = 1;
                    $add_data['end_time'] = time();
                    //新增一条罚金订单（支付后开门）
                    $order_id = M('order')->add($add_data);

                    $arr['status']=2;
                    $arr['order_id']=$order_id;
                    $arr['msg']='非法进入，请支付罚款金额，方可出门，如有疑问请咨询工作人员！';
                    exit(json_encode($arr));



//                    $this->success('非法进入，请支付罚款金额，方可出门，如有疑问请咨询工作人员！',U('Mobile/Cart/cart4',array('order_id'=>$order_id)),6);
                }
            }
            if(is_object($res)){

                if ($res->code == '0') {

                    $arr['status']=1;
                    $arr['msg']='欢迎再次光临';
                    exit(json_encode($arr));



//                    $this->error('欢迎再次光临',U('Mobile/Index/index'));
//                    $url=U('Mobile/Index/index');
//                    header("location:$url");


                } else {

                    $arr['status']=1;
                    $arr['msg']='-1002 网络连接失败，请重试！';
                    exit(json_encode($arr));


//                    $this->success('-1002 网络连接失败，请重试！',U('Mobile/Index/index'));
                }
            }elseif($res['status']=='-101'){

                $arr['status']=1;
                $arr['msg']='-1003 '.$res['msg'];
                exit(json_encode($arr));


//                $this->error('-1003 '.$res['msg'],U('Mobile/Index/index'));
            }
        }

        if ($res->code == '0') {
            $arr['status']=1;
            $arr['msg']='欢迎再次光临';
            exit(json_encode($arr));
//            $this->error('欢迎再次光临',U('Mobile/Index/index'));
        } else {
            $arr['status']=1;
            $arr['msg']='-1002 网络连接失败，请重试！';
            exit(json_encode($arr));
//            $this->success('-1002 网络连接失败，请重试！',U('Mobile/Index/index'));
        }
    }

}